package com.quasar.hpatient.view.prescription;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.change360.calendarview.CalendarDay;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.RemindMedicineTableItem;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.MedicineInfodb;
import com.quasar.hpatient.model.medicalmodel.MedicationRecordData;
import com.quasar.hpatient.model.medicalmodel.OnedayMedicationData;
import com.quasar.hpatient.onInterface.OnMedicationListener;
import com.quasar.hpatient.presenter.RemindMedicinePresenter;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.adapter.RemindMedicineAdapter;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringArrayRes;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 历史服药记录详情
 */
@EActivity(R.layout.activity_medication_record)
public class MedicationRecordActivity extends BaseActivity implements OnMedicationListener {

    private RemindMedicineAdapter remindMedicineAdapter;
    private RemindMedicinePresenter remindMedicinePresenter;
    Date dateTime;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @ViewById(R.id.tv_display_date)
    TextView tv_display_date;


    @ViewById(R.id.iv_search_date)
    ImageView iv_search_date;
    @StringArrayRes(R.array.medicineStats)
    String[] record_items;

    @Extra
    CalendarDay calendarDay;

    @ViewById(R.id.rv_list)
    RecyclerView rv_list;

    @AfterViews
    void init() {
        initView();
        initData();
    }


    @Override
    protected void initView() {
        initToolbar();
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);
    }

    @Override
    protected void initData() {
        dateTime = calendarDay.getDate();
        remindMedicinePresenter = new RemindMedicinePresenter(this);
        showDialog();
        //查询当日服药单信息
        remindMedicinePresenter.GetPatientSingleDoseDetailData(TimeZoneUtil.sdf.format(dateTime));
        tv_display_date.setText(format.format(dateTime));
    }

    //初始化adapter布局
    public void initAdapter(List<RemindMedicineTableItem> data) {
        remindMedicineAdapter = new RemindMedicineAdapter(data);
        rv_list.setAdapter(remindMedicineAdapter);

        remindMedicineAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (view.getId()) {
                    case R.id.remind_med_name:
                        ViseLog.d("输出的药品名称" + remindMedicineAdapter.getData().get(position).getName());
                        if (remindMedicineAdapter.getData().get(position).getName() != null) {
                            msg(remindMedicineAdapter.getData().get(position).getName());
                        }
                        break;

                    case R.id.remind_stats://一种服药

                        if (remindMedicineAdapter.getData().get(position) != null) {
                            RemindMedicineTableItem TableItem = remindMedicineAdapter.getData().get(position);
                            submitDialog(position, TableItem);
                        }

                        break;
                }
            }
        });

    }


    //一种服药信息提交Dialog
    public void submitDialog(final int postion, final RemindMedicineTableItem TableItem) {
        SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                int index = getSelectedIndex();

                switch (index) {
                    case ConstantManger.MEDICINEDIDNOTSUIT://未服
                        OneTakeMedicineInterface(postion, ConstantManger.MEDICINEDIDNOTSUIT + "", TableItem);
                        fragment.dismiss();
                        break;

                    case ConstantManger.MEDICINEBORMAL://正常
                        OneTakeMedicineInterface(postion, ConstantManger.MEDICINEBORMAL + "", TableItem);
                        fragment.dismiss();
                        break;


                    case ConstantManger.MEDICINETIMEOUT://超时
                        OneTakeMedicineInterface(postion, ConstantManger.MEDICINETIMEOUT + "", TableItem);
                        fragment.dismiss();
                        break;
//                    case ConstantManger.CANCEL://取消
//                        fragment.dismiss();
//                        break;
                }

            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
                fragment.dismiss();
            }
        };

        ((SimpleDialog.Builder) builder).items(record_items, 1)//0表示初始选中第一个
                .title("选择服药状态")
                .positiveAction("确认")
                .negativeAction("取消");
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getSupportFragmentManager(), null);
    }


    //一种服药接口调用
    public void OneTakeMedicineInterface(int position, String stats, RemindMedicineTableItem TableItem) {

        String id = remindMedicineAdapter.getData().get(position).getId() + "";
        String TimeData = TimeZoneUtil.sdf.format(new Date()).substring(10, 19);
        String DateTime = tv_display_date.getText().toString();
        //计算服药时间
        StringBuffer buffer = new StringBuffer();
        buffer.append(DateTime);
        buffer.append(" " + TimeData);
        ViseLog.d("服药的时间" + buffer.toString() + "****" + TimeData + "+++" + DateTime);
        dessDialog();
        remindMedicinePresenter.AddOneTakeMedicineData(stats, id, TableItem.getDetailId() + "", buffer.toString());
    }


    @Override
    public void onSuccess(AnotherResult<OnedayMedicationData> data) {
        ListDataVal(data);
        dessDialog();
    }

    //处理数据
    //保存当前服药单信息
    List<RemindMedicineTableItem> remindMedicineTableItem =new ArrayList<>();
    public void ListDataVal(AnotherResult<OnedayMedicationData> data) {
        if(stats==0){
            remindMedicineTableItem.clear();
        }

        if (data.getList().size() > 0 && data.getList() != null) {
            //查询当日服药单信息
            remindMedicineTableItem.clear();

            String TimeData = null;
            remindMedicineTableItem.add(new RemindMedicineTableItem(RemindMedicineTableItem.HEAD));//添加标题
            for (int i = 0; i < data.getList().size(); i++) {
                RemindMedicineTableItem remindMedi = new RemindMedicineTableItem();
                remindMedi.setItemType(RemindMedicineTableItem.BODY);//布局
                remindMedi.setId(data.getList().get(i).getId());//药品id
                remindMedi.setName(data.getList().get(i).getMName());//药品名称
                remindMedi.setDose(data.getList().get(i).getDoseName());//药品剂量
                remindMedi.setSpecifications(data.getList().get(i).getUseCount() + "");//药品规格
                remindMedi.setMedicineTime(data.getList().get(i).getUseTime().substring(10, 16));//服药时间
                remindMedi.setStats(data.getList().get(i).getStatus());//服药状态
                remindMedi.setDetailId(data.getList().get(i).getDetailId());//药单id
                remindMedicineTableItem.add(remindMedi);
                if (data.getList().get(i).getPatientDoseIndex() != null) {
                    if (data.getList().get(i).getPatientDoseIndex().getUseDateTime() != null) {
                        TimeData = data.getList().get(i).getPatientDoseIndex().getUseDateTime();
                    }
                }
            }

            if (data.getList().size() != 0) {
                if (TimeData != null) {
                    tv_display_date.setText(TimeData.substring(0, 10));
                    ViseLog.d("服药日期显示" + TimeData.substring(0, 10));
                }
            }
        }

        if(remindMedicineTableItem.size()==0){
            rl_isnotdata.setVisibility(View.VISIBLE);
        }else{
            rl_isnotdata.setVisibility(View.GONE);
        }
        initAdapter(remindMedicineTableItem);
    }

    @ViewById(R.id.rl_isnotdata)
    RelativeLayout rl_isnotdata;

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {
        dessDialog();
        remindMedicineAdapter.notifyDataSetChanged();
    }

    @Override
    public void onAddMutiTakeMedicine(DataStateResult dataStateResult) {

    }

    @Override
    public void AddOneTakeMedicine(DataStateResult dataStateResult) {

        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            //查询当日服药单信息
            remindMedicinePresenter.GetPatientSingleDoseDetailData(TimeZoneUtil.sdf.format(dateTime));
        }
    }

    @Override
    public void onSuccessMedicationRecordDate(AnotherResult<MedicationRecordData> data) {

    }

    int stats ;

    //上一天
    @Click(R.id.pre)
    public void pre() {
        stats=0;
        tv_display_date.setText(TimeZoneUtil.pre(tv_display_date.getText().toString(), 0));
        String time = tv_display_date.getText().toString();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(time);
        stringBuffer.append(" 00:00:00");
        showDialog();
        remindMedicinePresenter.GetPatientSingleDoseDetailData(stringBuffer.toString());
    }

    //下一天
    @Click(R.id.next)
    public void next() {
        stats=0;
        String times = tv_display_date.getText().toString();
        if (!times.equals(TimeZoneUtil.sdfFormat.format(new Date()))) {
            showDialog();
            tv_display_date.setText(TimeZoneUtil.pre(tv_display_date.getText().toString(), 1));
            String time = tv_display_date.getText().toString();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(time);
            stringBuffer.append(" 00:00:00");
            remindMedicinePresenter.GetPatientSingleDoseDetailData(stringBuffer.toString());
        }
    }

    //上一次
    @Click(R.id.iv_last)
    public void iv_last() {
        showDialog();
        stats=-1;
        String time = tv_display_date.getText().toString();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(time);
        stringBuffer.append(" 00:00:00");
        remindMedicinePresenter.GetlastPatientDoseIndexData(time);
    }

    //下一次
    @Click(R.id.iv_next)
    public void iv_next() {
        stats=-1;
        String time = tv_display_date.getText().toString();
        if (!time.equals(TimeZoneUtil.sdfFormat.format(new Date()))) {
            showDialog();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(time);
            stringBuffer.append(" 00:00:00");
            remindMedicinePresenter.GetNextPatientDoseIndexData(time);
        }
    }


    //    上次
    @Override
    public void OnSeccessLast(AnotherResult<OnedayMedicationData> data) {
        ListDataVal(data);
    }

    //    下次
    @Override
    public void OnSeccessNext(AnotherResult<OnedayMedicationData> data) {
        ListDataVal(data);
    }
}
